﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.Windows.Navigation;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Text.RegularExpressions;
using CommonControls.ClassFiles;
using System.Xml.Linq;
using System.ServiceModel;
using CommonControls.AboutApps;
using HomeBuyerTools.FileStoreService;
using HomeBuyerTools;
using HomeBuyerTools.ViewModels;

namespace CommonControls
{
    public partial class Feedback : PhoneApplicationPage
    {
        // Constructor
        string p;
       
        public static ImageSource povitTitle = null;
        public static ImageBrush Povitbg = null;
       
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        Service1Client myClient = new Service1Client();
        public Feedback()
        {
            InitializeComponent();

            LoadFeedbackTopics();
          
            Loaded += new RoutedEventHandler(Feedback_Loaded);
        }

      
        private void LoadFeedbackTopics()
        {
           
            List<MenuProperties> objfeedback = new List<MenuProperties>();
            XDocument xdoc = new XDocument();
          
                xdoc = XDocument.Load("FeedbackTopics.xml");
          

            var xquery = from i in xdoc.Descendants("topics") select i;
            foreach (var item in xquery)
            {
                MenuProperties objmenu = new MenuProperties();
                objmenu.Topics = item.Value;
                objfeedback.Add(objmenu);
            }
            TopicListPicker.ItemsSource = objfeedback;
        }

        void Feedback_Loaded(object sender, RoutedEventArgs e)
        {
            ImageBrush PanoramBrush = new ImageBrush();

            LoadPivotThemes();
            //PanoramBrush.ImageSource = new BitmapImage(new Uri(App.Back, UriKind.Relative));
            //PanoramBrush.Opacity = 0.6;
           // LayoutRoot.Background = PanoramBrush;
            string mid = "";
            string cno = "";
            string LinkType = "";
           
            string urii = "";
            string chtitle = "";
            if (NavigationContext.QueryString.TryGetValue("id", out mid) && NavigationContext.QueryString.TryGetValue("chno", out cno) && NavigationContext.QueryString.TryGetValue("LinkType", out LinkType) && NavigationContext.QueryString.TryGetValue("uri", out urii) && NavigationContext.QueryString.TryGetValue("title", out chtitle))
            {
               
                string str = "Movie Name : " + chtitle + "\n" +
                    cno + " \n " + "http://m.youtube.com/watch?v=" + urii + "\n";
                TopicListPicker.SelectedIndex = 1;
                txtboxFeedback.Text = str;


            }
            tbxMailId.Text = IsolatedSettings.getStringValue("FeedBackEmailId");

        }
        private void LoadPivotThemes()
        {
            LayoutRoot.Background = Custom.getPivotBackground();
            //imgTitle.Source = App.povitTitle;
        }
       
        private void ApplicationBarIconSendEmailButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (TopicListPicker.SelectedIndex != -1)
                {
                    if (txtboxFeedback.Text != "")
                    {
                        tblkMessageValidation.Visibility = Visibility.Collapsed;
                        string body = txtboxFeedback.Text + Exceptions.BuildMailMessage();
                        Service1Client service = new Service1Client();
                        string fromAddress = tbxMailId.Text;
                        string Toaddress = IsolatedSettings.getStringValue("ToEmailid");
                        if (Toaddress == "")
                        {
                            Toaddress = "feedback.at@Lartsoft.com";
                        }
                        if (fromAddress != "")
                        {
                            IsolatedSettings.save("FeedBackEmailId", fromAddress);
                            if (Regex.IsMatch(fromAddress, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
                            {
                                tblkMailIdValidation.Text = "(optional)";
                                tblkMailIdValidation.Foreground = new SolidColorBrush(Colors.White);
                                service.SendMailAsync(fromAddress, Toaddress, (TopicListPicker.SelectedItem as MenuProperties).Topics, body);
                                service.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(service_SendMailCompleted);
                               
                            }
                            else
                            {
                                tblkMailIdValidation.Text = "Please Enter Correct Mail Id";
                                tblkMailIdValidation.Foreground = new SolidColorBrush(Colors.Red);
                            }
                        }
                        else
                        {
                            fromAddress = IsolatedSettings.getStringValue("FromEmailid");
                            service.SendMailAsync(fromAddress, Toaddress, (TopicListPicker.SelectedItem as MenuProperties).Topics, body);
                            service.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(service_SendMailCompleted);
                        }
                    }
                    else
                        tblkMessageValidation.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                string excepmess = "Exception in ApplicationBarIconButton_Click Method In Feedback file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
                Exceptions.SaveExceptionInLocalStorage(excepmess);
            }
        }

        void service_SendMailCompleted(object sender, SendMailCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MessageBox.Show("Feedback sent successfully");
                if (PhoneHelper.GetAppAttribute("Title") == "Activity Tracker")
                {

                    NavigationService.Navigate(new Uri("/StartActivity.xaml", UriKind.Relative));
                }
                else if (PhoneHelper.GetAppAttribute("Title") == "HomeBuyerTools")
                {
                    NavigationService.Navigate(new Uri("/Views/Result/ResultPage.xaml", UriKind.Relative));
                }
                else
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            }
            else if (e.Error is FaultException)
            {
                MessageBox.Show("Failed to send feedback, try again later.");
                FaultException fault = e.Error as FaultException;
                Exceptions.SaveExceptionInLocalStorage(e.Error.Message);
            }
        }
        public class MenuProperties
        {
            private string _topics;
            public string Topics
            {
                get { return _topics; }
                set { _topics = value; }
            }
        }

    }
}